//
//  RegisterViewController.m
//  XDLBaseProject
//
//  Created by 谢东来 on 2019/8/29.
//  Copyright © 2019 Apple. All rights reserved.
//

#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "ForgetPasswordViewController.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@property (strong, nonatomic) UITextField *zhanghaoInput;
@property (strong, nonatomic) UITextField *mimaInput;

@end

@implementation RegisterViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setSubviews];
    
    if ([DataManager shareManager].dataModel.zhanghao.length > 0) {
        self.zhanghaoInput.text = [DataManager shareManager].dataModel.zhanghao;
        self.mimaInput.text = [DataManager shareManager].dataModel.mima;
    }
//    [self versionsUpdate];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil];
}

//- (void)versionsUpdate {
//    WeakSelf(weakSelf)
//    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
//    //当前版本号
//    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"当前版本号%@",currentVersion);
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *parameters = @{};
//    [manager POST:API_VERSIONS parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
//        if ([responseObject[@"status"] integerValue] == 1) {
//            NSDictionary *dic = responseObject[@"result"];
//            NSString *newVersion = dic[@"versions"];
//            if (![newVersion isEqualToString:currentVersion]) {
//                //需要強制更新
//                [weakSelf versionsUpdateAction];
//            }
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@", error);
//    }];
//}

//- (void)versionsUpdateAction {
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"發現新版本，請更新！" preferredStyle:(UIAlertControllerStyleAlert)];
//                    UIAlertAction * alertAction = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                        //跳轉appstore
//                        //苹果商店下载页面
//                        NSString*str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%d",1483083984];
////                        NSString *str = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%d",1483083984];
//                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:^(BOOL success) {
//                            [self versionsUpdateAction];
//                        }];
//                    }];
//                    //弹框按钮
//    [alert addAction:alertAction];
//    [self presentViewController:alert animated:YES completion:nil];
//}

- (void)setSubviews {
//    UIImageView *imV = [[UIImageView alloc] initWithFrame:(CGRectMake(0, 0, kScreenW, kScreenH))];
//    imV.image = [UIImage imageNamed:@"loginbg.png"];
//    imV.contentMode = UIViewContentModeScaleAspectFill;
//    [self.view addSubview:imV];
    
    UIImageView *logoImV = [[UIImageView alloc] init];
    logoImV.image = [UIImage imageNamed:@"mainIcon.jpg"];
    logoImV.backgroundColor = [AppColor getColor_MAIN];
    logoImV.contentMode = UIViewContentModeScaleAspectFill;
    logoImV.layer.cornerRadius = Width_Real(45);
    logoImV.layer.borderColor = [AppColor getColor_MAIN].CGColor;
    logoImV.layer.borderWidth = Width_Real(2);
    logoImV.layer.masksToBounds = YES;
    [self.view addSubview:logoImV];
    [logoImV autoSetDimensionsToSize:(CGSizeMake(Width_Real(90), Width_Real(90)))];
    [logoImV autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [logoImV autoPinEdgeToSuperviewEdge:(ALEdgeTop) withInset:Y_Real(100)];
    
    UIView *zhanghaoV = [[UIView alloc] init];
    zhanghaoV.layer.cornerRadius = Height_Real(25);
    zhanghaoV.layer.borderWidth = Width_Real(1.5);
    zhanghaoV.layer.borderColor = [AppColor getColor_MAIN].CGColor;
    zhanghaoV.layer.masksToBounds = YES;
    [self.view addSubview:zhanghaoV];
    [zhanghaoV autoSetDimensionsToSize:(CGSizeMake(kScreenW - Width_Real(60), Height_Real(50)))];
    [zhanghaoV autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [zhanghaoV autoPinEdge:(ALEdgeTop) toEdge:(ALEdgeBottom) ofView:logoImV withOffset:Y_Real(80)];
    UIImageView *zhanghaoImv = [[UIImageView alloc] init];
    zhanghaoImv.backgroundColor = [AppColor getColor_MAIN];
    zhanghaoImv.layer.cornerRadius = Width_Real(15);
    [zhanghaoV addSubview:zhanghaoImv];
    [zhanghaoImv autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [zhanghaoImv autoPinEdgeToSuperviewEdge:(ALEdgeLeft) withInset:X_Real(15)];
    [zhanghaoImv autoSetDimensionsToSize:(CGSizeMake(Width_Real(30), Width_Real(30)))];
    zhanghaoImv.contentMode = UIViewContentModeScaleAspectFill;
    UIImageView *zhanghaoImv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zhanghao.png"]];
    [zhanghaoImv addSubview:zhanghaoImv2];
    [zhanghaoImv2 autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [zhanghaoImv2 autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [zhanghaoImv2 autoSetDimensionsToSize:(CGSizeMake(Width_Real(20), Width_Real(20)))];
    zhanghaoImv2.contentMode = UIViewContentModeScaleAspectFill;
    UITextField *zhanghaoInput = [[UITextField alloc] init];
    zhanghaoInput.delegate = self;
    self.zhanghaoInput = zhanghaoInput;
    zhanghaoInput.inputAccessoryView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenW, Height_Real(0.01)))];
    zhanghaoInput.keyboardType = UIKeyboardTypeAlphabet;
    zhanghaoInput.textColor = [UIColor blackColor];
    [zhanghaoInput setFont:[AppFont getFont_16]];
    NSDictionary *dic = @{NSForegroundColorAttributeName:[UIColor lightGrayColor], NSFontAttributeName:[AppFont getFont_16]};
    zhanghaoInput.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入邮箱" attributes:dic];
    [zhanghaoInput addTarget:self action:@selector(textEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [zhanghaoV addSubview:zhanghaoInput];
    [zhanghaoInput autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [zhanghaoInput autoPinEdge:(ALEdgeLeft) toEdge:(ALEdgeRight) ofView:zhanghaoImv withOffset:Y_Real(20)];
    [zhanghaoInput autoPinEdgeToSuperviewEdge:(ALEdgeTop) withInset:Y_Real(5)];
    [zhanghaoInput autoPinEdgeToSuperviewEdge:(ALEdgeBottom) withInset:Y_Real(5)];
    [zhanghaoInput autoPinEdgeToSuperviewEdge:(ALEdgeRight) withInset:X_Real(25)];
    
    UIView *mimaV = [[UIView alloc] init];
    mimaV.layer.cornerRadius = Height_Real(25);
    mimaV.layer.borderWidth = Width_Real(1.5);
    mimaV.layer.borderColor = [AppColor getColor_MAIN].CGColor;
    mimaV.layer.masksToBounds = YES;
    [self.view addSubview:mimaV];
    [mimaV autoSetDimensionsToSize:(CGSizeMake(kScreenW - Width_Real(60), Height_Real(50)))];
    [mimaV autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [mimaV autoPinEdge:(ALEdgeTop) toEdge:(ALEdgeBottom) ofView:zhanghaoV withOffset:Y_Real(20)];
    UIImageView *mimaImv = [[UIImageView alloc] init];
    mimaImv.backgroundColor = [AppColor getColor_MAIN];
    mimaImv.layer.cornerRadius = Width_Real(15);
    [mimaV addSubview:mimaImv];
    [mimaImv autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [mimaImv autoPinEdgeToSuperviewEdge:(ALEdgeLeft) withInset:X_Real(15)];
    [mimaImv autoSetDimensionsToSize:(CGSizeMake(Width_Real(30), Width_Real(30)))];
    mimaImv.contentMode = UIViewContentModeScaleAspectFill;
    UIImageView *mimaImv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mima.png"]];
    [mimaImv addSubview:mimaImv2];
    [mimaImv2 autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [mimaImv2 autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [mimaImv2 autoSetDimensionsToSize:(CGSizeMake(Width_Real(18), Width_Real(18)))];
    mimaImv2.contentMode = UIViewContentModeScaleAspectFill;
    UITextField *mimaInput = [[UITextField alloc] init];
    mimaInput.delegate = self;
    self.mimaInput = mimaInput;
    mimaInput.inputAccessoryView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kScreenW, Height_Real(0.01)))];
    mimaInput.keyboardType = UIKeyboardTypeAlphabet;
    mimaInput.returnKeyType = UIReturnKeyDone;
    mimaInput.autocorrectionType = UITextAutocorrectionTypeNo;
    mimaInput.autocapitalizationType = UITextAutocapitalizationTypeNone;
    mimaInput.secureTextEntry = YES;
    mimaInput.textColor = [UIColor blackColor];
    [mimaInput setFont:[AppFont getFont_16]];
    dic = @{NSForegroundColorAttributeName:[UIColor lightGrayColor], NSFontAttributeName:[AppFont getFont_16]};
    mimaInput.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dic];
    [mimaInput addTarget:self action:@selector(textEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [mimaV addSubview:mimaInput];
    [mimaInput autoAlignAxisToSuperviewAxis:(ALAxisHorizontal)];
    [mimaInput autoPinEdge:(ALEdgeLeft) toEdge:(ALEdgeRight) ofView:mimaImv withOffset:Y_Real(20)];
    [mimaInput autoPinEdgeToSuperviewEdge:(ALEdgeTop) withInset:Y_Real(5)];
    [mimaInput autoPinEdgeToSuperviewEdge:(ALEdgeBottom) withInset:Y_Real(5)];
    [mimaInput autoPinEdgeToSuperviewEdge:(ALEdgeRight) withInset:X_Real(20)];
    
//    UIButton *forgetMima = [[UIButton alloc] init];
//    [forgetMima setTitle:@"忘记密码" forState:(UIControlStateNormal)];
//    [forgetMima setTitleColor:[AppColor getColor_MAIN] forState:(UIControlStateNormal)];
//    forgetMima.titleLabel.font = [AppFont getFont_11];
//    [forgetMima addTarget:self action:@selector(clickForgetMima) forControlEvents:(UIControlEventTouchUpInside)];
//    [self.view addSubview:forgetMima];
//    [forgetMima autoPinEdge:(ALEdgeLeft) toEdge:(ALEdgeLeft) ofView:mimaV];
//    [forgetMima autoPinEdge:(ALEdgeTop) toEdge:(ALEdgeBottom) ofView:mimaV withOffset:Y_Real(5)];
//    [forgetMima autoSetDimensionsToSize:(CGSizeMake(Width_Real(60), Height_Real(30)))];
    
    UIButton *signIn = [[UIButton alloc] init];
    [signIn setTitle:@"注册账号" forState:(UIControlStateNormal)];
    [signIn setTitleColor:[AppColor getColor_MAIN] forState:(UIControlStateNormal)];
    signIn.titleLabel.font = [AppFont getFont_11];
    [signIn addTarget:self action:@selector(clickSignIn) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:signIn];
    [signIn autoPinEdge:(ALEdgeRight) toEdge:(ALEdgeRight) ofView:mimaV];
    [signIn autoPinEdge:(ALEdgeTop) toEdge:(ALEdgeBottom) ofView:mimaV withOffset:Y_Real(5)];
    [signIn autoSetDimensionsToSize:(CGSizeMake(Width_Real(60), Height_Real(30)))];
    
    UIButton *loginBtn = [[UIButton alloc] init];
    [loginBtn setBackgroundImage:[UIImage imageWithColor:[AppColor getColor_MAIN] size:CGSizeMake(kScreenW - Width_Real(60), Height_Real(50))] forState:(UIControlStateNormal)];
    [loginBtn setTitle:@"登    录" forState:(UIControlStateNormal)];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    loginBtn.titleLabel.font = [AppFont getFont_19];
    loginBtn.layer.cornerRadius = Height_Real(25);
    loginBtn.layer.masksToBounds = YES;
    [loginBtn addTarget:self action:@selector(clickLogin) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:loginBtn];
    [loginBtn autoSetDimensionsToSize:(CGSizeMake(kScreenW - Width_Real(60), Height_Real(50)))];
    [loginBtn autoAlignAxisToSuperviewAxis:(ALAxisVertical)];
    [loginBtn autoPinEdge:(ALEdgeTop) toEdge:(ALEdgeBottom) ofView:mimaV withOffset:Y_Real(60)];
    
    #pragma mark - 测试
    zhanghaoInput.text = @"admin@admin.com";
    mimaInput.text = @"12345678Aa!";
}


- (void)clickLogin {
    [self.view endEditing:YES];
    if (self.mimaInput.text.length < 8){
        [SVProgressHUD showErrorWithStatus:@"密码最少应为8位"];
    } else {
        [SVProgressHUD show];
        WeakSelf(weakSelf)
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSDictionary *parameters = @{@"email":self.zhanghaoInput.text,
                                     @"password":self.mimaInput.text};
        [manager DL_POST:API_LOGIN parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
            NSDictionary *data = responseObject[@"data"];
            if ([responseObject[@"code"] integerValue] == 1) {
                if (data[@"token"]) {
                    [DataManager shareManager].dataModel.token = data[@"token"];
                    [weakSelf gettUserTypeWithToken:data[@"token"] complete:^{
                        [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                        [weakSelf dismissViewControllerAnimated:YES completion:^{
                            //
                        }];
                    }];
                }
            } else {
                [SVProgressHUD showErrorWithStatus:responseObject[@"info"]];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        }];
    }
}

- (void)gettUserTypeWithToken:(NSString *)token complete:(void(^)(void))complete {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *parameters = @{@"token":token};
    [manager DL_POST:API_GETUSERTYPE parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSDictionary *data = responseObject[@"data"];
        if ([data[@"UserType"] integerValue] == 0) {
            [DataManager shareManager].dataModel.isSpecialUser = NO;
        } else {
            [DataManager shareManager].dataModel.isSpecialUser = YES;
        }
        complete();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        [DataManager shareManager].dataModel.isSpecialUser = NO;
        complete();
    }];
}

- (void)judgeTodayNum {
    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"MMdd"];
//    NSDate *now = [NSDate date];
//    NSString *dateStr = [dateFormatter stringFromDate:now];
//    if (![[DataManager shareManager].dataModel.todayDate isEqualToString:dateStr]) {
//        [DataManager shareManager].dataModel.todayDate = [NSString stringWithString:dateStr];
//        [DataManager shareManager].dataModel.todayNum = 2;
//        [DataManager shareManager].dataModel.todayProfit = 0;
//        [[DataManager shareManager].dataModel.zhexianArr addObject:@0];
//        [[DataManager shareManager] saveData];
//    }
}

//- (void)sendNetwork {
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *parameters = @{@"zhanghao":@"18601946832"};
//    [manager POST:API_GETUSERINFO parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@", error);
//    }];
//}

- (void)clickForgetMima {
    [self.view endEditing:YES];
    ForgetPasswordViewController *v = [[ForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:v animated:YES];
}

- (void)clickSignIn {
    [self.view endEditing:YES];
    LoginViewController *v = [[LoginViewController alloc] init];
    [self.navigationController pushViewController:v animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if (textField == self.mimaInput) {
//        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
//        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
//        return [string isEqualToString:filtered];
//    } else if (textField == self.zhanghaoInput) {
//        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];
//        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
//        return [string isEqualToString:filtered];
//    } else {
//        return NO;
//    }
//}

- (void)textEditingChanged:(UITextField *)textField {
    if (textField == self.zhanghaoInput || textField == self.mimaInput) {
        if ([textField.text length] > 25) {
            textField.text = [textField.text substringToIndex:25];
        }
    }
}

- (void)dealloc {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"登錄頁面消失");
}


//- (void)textFieldDidBeginEditing:(UITextField *)textField {
//    textField.secureTextEntry = YES;
//}
//
//- (void)keyboardWillShow {
//    if (self.zhanghaoInput.secureTextEntry == YES) {
//        self.zhanghaoInput.secureTextEntry = NO;
//    }
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
